/* -------------------------------------------------------- Function -- */
import { existHttp } from './utils'
/* -------------------------------------------------------- Declare -- */
const { $fn } = window
/**
 * 简单模式下，默认选中第一个
 * @param {Array} data	# 菜单数据
 * @return {Array} 		# 新的菜单数据
 */
const setEasyFirstRouter = data => {
	const deep = data => {
		if( $fn.hasArray( data ) ){
			let { children } = data[0]
			data[0].checked = true
			if( $fn.hasArray(children) ){ return setEasyFirstRouter( children ) }
		}
	}
	deep(data)
	return data
}
/**
 * 将菜单数据中的 path 拼合成有效 path，并默认选中
 * @param {Array} 	data		# 菜单数据
 * @param {String} 	rootPath	# 根路由，如: /main
 * @param {Boolean} openAll 	# 是否展开全部
 * @return {Array} 				# 新的菜单数据
 */
const Index = (data, rootPath=window.$config?.menu?.root, openAll=window.$config?.menu?.open) => {
	let hash = window.location.hash.replace('#','')
	let root = rootPath ? '/' + rootPath + '/' : ''
	
	const deep = (data, path) => {
		if(path && path.substr(-1) === '/') path = path.substr(0, path.length - 1)
		data.forEach( v => {
			const { url, name, children, child } = v
			if( url ){
				if( existHttp(url) ){
					v.path = url
				}else{
					if( root && root !== '' ){
						v.path = url.startsWith(root) ? url : root + url
					}else{
						v.path = url
					}
				}
			}else{
				if(v.path){
					if( root && root !== '' && existHttp(v.path)){
						v.path = v.path.startsWith(root) ? v.path : root + path
					}
				}else{
					if( name ){ 
						// path =  path.startsWith(root) ? path : root + v.path
						v.path = path + '/' + name 
					}
				}
			}
			if(Array.isArray(children)) {
				v.checked = openAll ? true : hash.startsWith(v.path + '/')
				deep(children, v.path)
			}else{
				v.checked = openAll ? true : hash === v.path || hash.startsWith(v.path + '/')
				
				if( Array.isArray( child ) ){
					v.outlet = true
					// const component = v.component ? { component:v.component } : null
					// v.child.unshift({ title, name, path:v.path, ...component, cache:true })
					deep(child, v.path, true)
				}
			}
		})
		return data
	}
	data = deep( data, root )
	$fn.session('menu', data)
	// 标记 /main 重定向后的位置
	if(hash === '/' + rootPath) data = setEasyFirstRouter(data)
	return data
}
export default Index